/**
 * 聊天历史管理器
 */

class ChatHistory {
  
  /**
   * 获取聊天历史
   * @returns {Array} 聊天历史数组
   */
  static getChatHistory() {
    try {
      const history = uni.getStorageSync('chatHistory') || []
      return history
    } catch (error) {
      console.log('获取聊天历史失败:', error)
      return []
    }
  }
  
  /**
   * 添加聊天消息
   * @param {Object} message 消息对象
   */
  static addMessage(message) {
    try {
      const history = this.getChatHistory()
      
      const chatMessage = {
        id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
        timestamp: new Date().toISOString(),
        type: message.type || 'text', // text, game, movie, system
        content: message.content || '',
        sender: message.sender || 'user', // user, system, ai
        data: message.data || null, // 额外数据，如游戏对象、电影对象等
        category: message.category || 'general' // 消息分类
      }
      
      // 添加到历史记录开头
      history.unshift(chatMessage)
      
      // 限制历史记录数量（最多保留1000条）
      if (history.length > 1000) {
        history.splice(1000)
      }
      
      uni.setStorageSync('chatHistory', history)
      console.log('聊天消息已保存:', chatMessage)
      
      return chatMessage
      
    } catch (error) {
      console.log('保存聊天消息失败:', error)
      return null
    }
  }
  
  /**
   * 删除指定消息
   * @param {string} messageId 消息ID
   */
  static removeMessage(messageId) {
    try {
      const history = this.getChatHistory()
      const filteredHistory = history.filter(item => item.id !== messageId)
      uni.setStorageSync('chatHistory', filteredHistory)
      return true
    } catch (error) {
      console.log('删除聊天消息失败:', error)
      return false
    }
  }
  
  /**
   * 清空聊天历史
   */
  static clearChatHistory() {
    try {
      uni.removeStorageSync('chatHistory')
      return true
    } catch (error) {
      console.log('清空聊天历史失败:', error)
      return false
    }
  }
  
  /**
   * 根据类型获取消息
   * @param {string} type 消息类型
   * @returns {Array} 指定类型的消息
   */
  static getMessagesByType(type) {
    const history = this.getChatHistory()
    return history.filter(item => item.type === type)
  }
  
  /**
   * 根据分类获取消息
   * @param {string} category 消息分类
   * @returns {Array} 指定分类的消息
   */
  static getMessagesByCategory(category) {
    const history = this.getChatHistory()
    return history.filter(item => item.category === category)
  }
  
  /**
   * 搜索聊天记录
   * @param {string} keyword 关键词
   * @returns {Array} 匹配的消息
   */
  static searchMessages(keyword) {
    const history = this.getChatHistory()
    const lowerKeyword = keyword.toLowerCase()
    
    return history.filter(item => 
      item.content.toLowerCase().includes(lowerKeyword) ||
      (item.data && item.data.name && item.data.name.toLowerCase().includes(lowerKeyword))
    )
  }
  
  /**
   * 获取最近的消息
   * @param {number} count 数量
   * @returns {Array} 最近的消息
   */
  static getRecentMessages(count = 50) {
    const history = this.getChatHistory()
    return history.slice(0, count)
  }
  
  /**
   * 格式化消息时间
   * @param {string} timestamp ISO时间戳
   * @returns {string} 格式化后的时间
   */
  static formatMessageTime(timestamp) {
    const date = new Date(timestamp)
    const now = new Date()
    const diff = now - date
    
    // 如果是今天
    if (date.toDateString() === now.toDateString()) {
      return date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
    }
    
    // 如果是昨天
    const yesterday = new Date(now)
    yesterday.setDate(now.getDate() - 1)
    if (date.toDateString() === yesterday.toDateString()) {
      return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
    }
    
    // 其他日期
    return date.toLocaleDateString('zh-CN') + ' ' + 
           date.toLocaleTimeString('zh-CN', { 
             hour: '2-digit', 
             minute: '2-digit' 
           })
  }
  
  /**
   * 导出聊天记录
   * @returns {string} JSON格式的聊天记录
   */
  static exportChatHistory() {
    try {
      const history = this.getChatHistory()
      return JSON.stringify(history, null, 2)
    } catch (error) {
      console.log('导出聊天记录失败:', error)
      return ''
    }
  }
  
  /**
   * 导入聊天记录
   * @param {string} jsonData JSON格式的聊天记录
   * @returns {boolean} 是否成功
   */
  static importChatHistory(jsonData) {
    try {
      const importedHistory = JSON.parse(jsonData)
      
      if (Array.isArray(importedHistory)) {
        uni.setStorageSync('chatHistory', importedHistory)
        return true
      }
      
      return false
    } catch (error) {
      console.log('导入聊天记录失败:', error)
      return false
    }
  }
  
  /**
   * 获取统计信息
   * @returns {Object} 统计数据
   */
  static getStatistics() {
    const history = this.getChatHistory()
    
    const stats = {
      totalMessages: history.length,
      textMessages: 0,
      gameMessages: 0,
      movieMessages: 0,
      systemMessages: 0,
      todayMessages: 0,
      weekMessages: 0
    }
    
    const now = new Date()
    const today = now.toDateString()
    const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
    
    history.forEach(message => {
      // 统计类型
      switch (message.type) {
        case 'text':
          stats.textMessages++
          break
        case 'game':
          stats.gameMessages++
          break
        case 'movie':
          stats.movieMessages++
          break
        case 'system':
          stats.systemMessages++
          break
      }
      
      // 统计时间
      const messageDate = new Date(message.timestamp)
      if (messageDate.toDateString() === today) {
        stats.todayMessages++
      }
      if (messageDate >= weekAgo) {
        stats.weekMessages++
      }
    })
    
    return stats
  }
}

export default ChatHistory